package com.hfzy.ihk.web.linkcall.support.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.CustomerAnswerWay;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlowStep;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase;
import com.hfzy.ihk.facade.linkcall.enums.Bool;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.KnowledgeBaseVo;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.KnowledgeBaseBiz;
import com.hfzy.ihk.web.linkcall.constant.RedisKey;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.rmi.CORBA.Util;
import java.util.*;

/**
 *  此类是 有 @PushMsgToAIService 注解 方法的切面
 * */
@Aspect
@Component
public class PushMsgToAIServiceHandle {
    private static final Logger logger = LoggerFactory.getLogger(PushMsgToAIServiceHandle.class);

    @Value("${aiService.knowledgebase.analysis.singleCall.url}")
    public String singleCallUrl;

    @Value("${aiService.knowledgebase.analysis.basicFunc.url}")
    public String basicFuncUrl;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    KnowledgeBaseBiz knowledgeBaseBiz;

    //切入 到 引用注解 的方法中
    @Pointcut("@annotation(com.hfzy.ihk.web.linkcall.support.annotation.PushMsgToAIService)")
    public void pointCutFun(){};



    @AfterReturning(value = "pointCutFun()",returning="returnObj")
    public void pointCutFunAfter(JoinPoint joinPoint,Object returnObj){
        logger.debug("推送信息到ai服务");
        String pushId = "";//推送的id值
        boolean pushAiServiceUpdateKnowledge = false;
        List<Map> rePushMaps = new ArrayList<Map>();
        try{
            Object[] args = joinPoint.getArgs();
            String funName = joinPoint.getSignature().getName();
            String result = ""; //推送返回的结果值
            boolean flag = false; //是否进行推送消息

            List<Map> pushAIDatas = new ArrayList<>();
            switch (funName){
                /*知识库*/
                case "updateSomeFields":
                    if(args!=null && args.length>0 && args[0] instanceof String && returnObj instanceof Boolean){
                        pushId = (String)args[0];
                        flag = (Boolean) returnObj;
                        KnowledgeBase knowledgeBase = knowledgeBaseBiz.selectById(pushId);
                        Map jsonMap = new HashMap();
                        jsonMap.put("key","knowledge");
                        jsonMap.put("value",JSON.toJSONString(new HashMap(){{put("update_id",knowledgeBase.getId());put("update_data",JSON.toJSONString(knowledgeBase));}}));
                        pushAIDatas.add(jsonMap);
                    }
                    break;
                case "esDeleteById":
                    if(args!=null && args.length>0 && args[0] instanceof String && returnObj instanceof WebResult){
                        pushId = (String)args[0];
                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }

                        Map jsonMap = new HashMap();
                        jsonMap.put("knowledge",JSON.toJSONString(new HashMap(){{put("update_id",args[0]);put("update_data",JSON.toJSONString(new Object()));}}));
                        pushAIDatas.add(jsonMap);
                    }
                    break;
                case "baseInsert":
                case "esAdd":
                    if(args!=null && args.length>0 && args[0] instanceof KnowledgeBase && returnObj instanceof Boolean) {
                        KnowledgeBase knowledgeBase = ((KnowledgeBase) args[0]);
                        pushId = knowledgeBase.getId();
                        flag = (Boolean) returnObj;

                        Map jsonMap = new HashMap();
                        jsonMap.put("knowledge",JSON.toJSONString(new HashMap(){{put("update_id",knowledgeBase.getId());put("update_data",JSON.toJSONString(knowledgeBase));}}));
                        pushAIDatas.add(jsonMap);
                    }
                    break;
                    /*流程*/
                case "addSpeakingFlow":
                case "saveSpeakingFlow":
                    if(args!=null && args[0] instanceof SpeakingFlow && returnObj instanceof WebResult){
                        SpeakingFlow speakingFlow = ((SpeakingFlow) args[0]);
                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                        Map jsonMap = new HashMap();
                        jsonMap.put("flow",JSON.toJSONString(new HashMap(){{put("update_id",speakingFlow.getId());put("update_data",JSON.toJSONString(speakingFlow));}}));
                        pushAIDatas.add(jsonMap);
                    }
                    break;
                case "deleteSpeakingFlowById":
                    if(args!=null && args.length >0 && args[0] instanceof String && returnObj instanceof WebResult){
                        Map jsonMap = new HashMap();
                        jsonMap.put("flow",JSON.toJSONString(new HashMap(){{put("update_id",args[0]);put("update_data",JSON.toJSONString(new Object()));}}));
                        pushAIDatas.add(jsonMap);
                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                    }
                    break;
                case "saveFlows":
                    if(args!=null && args.length >0 && args[0] instanceof SpeakingFlow && returnObj instanceof WebResult){
                        SpeakingFlow speakingFlow = ((SpeakingFlow) args[0]);

                        Map jsonMap = new HashMap();
                        jsonMap.put("flow",JSON.toJSONString(new HashMap(){{put("update_id",speakingFlow.getId());put("update_data",JSON.toJSONString(speakingFlow));}}));
                        pushAIDatas.add(jsonMap);

                        if(args[1] instanceof List){
                            List<SpeakingFlowStep> speakingFlowSteps = (List<SpeakingFlowStep>)args[1];
                            for(SpeakingFlowStep speakingFlowStep:speakingFlowSteps){
                                Map flowStepMap = new HashMap();
                                flowStepMap.put("flow_step",JSON.toJSONString(new HashMap(){{put("update_id",speakingFlowStep.getId());put("update_data",JSON.toJSONString(speakingFlowStep));}}));
                                pushAIDatas.add(flowStepMap);
                            }
                        }

                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                    }
                    break;
                    /* 流程步骤*/
                case "addSpeakingFlowStep":
                case "saveSpeakingFlowStep":
                    if(args!=null && args[0] instanceof SpeakingFlowStep && returnObj instanceof WebResult){
                        SpeakingFlowStep speakingFlowStep = ((SpeakingFlowStep) args[0]);

                        Map jsonMap = new HashMap();
                        jsonMap.put("flow_step",JSON.toJSONString(new HashMap(){{put("update_id",speakingFlowStep.getId());put("update_data",JSON.toJSONString(speakingFlowStep));}}));
                        pushAIDatas.add(jsonMap);

                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                    }
                    break;
                case "deleteSpeakingFlowStepById":
                    if(args!=null && args.length >0 && args[0] instanceof String && returnObj instanceof WebResult){
                        Map jsonMap = new HashMap();
                        jsonMap.put("flow_step",JSON.toJSONString(new HashMap(){{put("update_id",args[0]);put("update_data",JSON.toJSONString(new Object()));}}));
                        pushAIDatas.add(jsonMap);
                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                    }
                    break;
                case "addSpeakingFlowStepList":
                case "updateSpeakingFlowStepList":
                    if(args!=null && args[0] instanceof List && returnObj instanceof Boolean){
                        List<SpeakingFlowStep> speakingFlowSteps = ((List<SpeakingFlowStep>) args[0]);
                        for(SpeakingFlowStep speakingFlowStep : speakingFlowSteps){
                            Map jsonMap = new HashMap();
                            jsonMap.put("flow_step",JSON.toJSONString(new HashMap(){{put("update_id",speakingFlowStep.getId());put("update_data",speakingFlowStep);}}));
                            pushAIDatas.add(jsonMap);
                        }
                        flag = (Boolean)returnObj;
                    }
                    break;
                    /*自定义分支*/
                case "addCustomerAnswerWay":
                case "saveCustomerAnswerWay":
                    if(args!=null && args[0] instanceof CustomerAnswerWay && returnObj instanceof WebResult){
                        CustomerAnswerWay customerAnswerWay = ((CustomerAnswerWay) args[0]);
                        Map jsonMap = new HashMap();
                        jsonMap.put("answer_way",JSON.toJSONString(new HashMap(){{put("update_id",customerAnswerWay.getId());put("update_data",customerAnswerWay);}}));
                        pushAIDatas.add(jsonMap);
                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                    }
                    break;
                case "deleteCustomerAnswerWayById":
                    if(args!=null && args.length >0 && args[0] instanceof String && returnObj instanceof WebResult){
                        Map jsonMap = new HashMap();
                        jsonMap.put("answer_way",JSON.toJSONString(new HashMap(){{put("update_id",args[0]);put("update_data",new Object());}}));
                        pushAIDatas.add(jsonMap);
                        WebResult webResult = (WebResult) returnObj;
                        if(GlobalStatic.CODE_1.equals(webResult.getCode())){
                            flag = true;
                        }
                    }
                    break;
                default:
                    break;
            }

            //todo 以下的暂时不推  接口未通
              /*result = HttpClientUtils.getMethod(singleCallUrl + "/knowledgebase/" + pushId);
                if(result == null || Utils.isNullString(result) || !"true".equals(result)){//解析接受到的结果集，如果判断为异常情况下，再次进行重推操作
                    //异常的情况的话 ---》 会导致阻塞？？ --》 定期发有用，没发的话有影响？
                    //通过redis 将需要进行重发的 pushId 存起来==》进行定时重发操作，发完后，移除原存在的pushId
                    redisTemplate.opsForSet().add(RedisKey.RE_ADVICE_LOAD_KNOWLEDGE_BASE_IDS,pushId);
                }*/
               /* if(flag &&  (pushAIDatas!=null && !pushAIDatas.isEmpty())){
                    pushAiServiceUpdateKnowledge = true;
                    for(Map map : pushAIDatas){
                        String rs = HttpClientUtils.postMethod(basicFuncUrl + "/data_manager",map,null);
                        if(rs == null || Utils.isNullString(rs) || !"true".equals(rs)){//解析接受到的结果集，如果判断为异常情况下，再次进行重推操作
                            rePushMaps.add(map);//失败的话将其存起来
                        }
                    }
                    if(rePushMaps!=null && !rePushMaps.isEmpty())
                        redisTemplate.opsForSet().add(RedisKey.RE_ADVICE_UPDATE_DATA_TO_AI_SERVER,JSON.toJSONString(rePushMaps));
                }*/
        }catch (Exception e){
            e.printStackTrace();
            logger.error("推送信息到ai服务异常,"+e.getMessage());
            if(pushAiServiceUpdateKnowledge  && rePushMaps!=null && !rePushMaps.isEmpty()){
                redisTemplate.opsForSet().add(RedisKey.RE_ADVICE_UPDATE_DATA_TO_AI_SERVER,JSON.toJSONString(rePushMaps));
            }
        }
    }
}
